<template>
  <j-modal
    :title="title"
    :width="width"
    :visible="visible"
    :confirmLoading="confirmLoading"
    switchFullscreen
    @ok="handleOk"
    @cancel="handleCancel">
    <a-spin :spinning="confirmLoading">
      <a-form :form="form">
        <!-- 物料类型选择 -->
        <a-form-item label="物料类型" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <j-dict-select-tag
            type="list"
            v-decorator="['materialType', validatorRules.materialType]"
            :triggerChange="true"
            dictCode="material_type"
            @change="handleMaterialTypeChange"
            :disabled="disableEdit" />
        </a-form-item>

        <!-- 通用字段 -->
        <a-form-item :label="getMaterialLabel('code')" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-input :placeholder="`请输入${getMaterialLabel('code')}`" v-decorator="['materialCode', validatorRules.materialCode]" :disabled="disableEdit" />
        </a-form-item>
        <a-form-item :label="getMaterialLabel('name')" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-input :placeholder="`请输入${getMaterialLabel('name')}`" v-decorator="['materialName', validatorRules.materialName]" />
        </a-form-item>
        <a-form-item label="物料图片" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <j-image-upload
            v-decorator="['materialImage']"
            :number="1"
            :bizPath="getBizPath()"
            :returnUrl="true"
            @change="handleImageChange"
            @error="handleImageError"></j-image-upload>
        </a-form-item>

        <!-- 通用规格 -->
        <a-form-item label="规格型号" :labelCol="labelCol" :wrapperCol="wrapperCol" v-if="showField('specification')">
          <a-input placeholder="请输入规格型号" v-decorator="['specification']" />
        </a-form-item>
        <a-form-item label="单位" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-input placeholder="请输入单位" v-decorator="['unit', validatorRules.unit]" />
        </a-form-item>

        <a-form-item label="单位成本" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-input-number style="width: 100%" placeholder="请输入单位成本" v-decorator="['unitCost']" :precision="2" :min="0" />
        </a-form-item>

        <a-form-item label="预警上限" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-input-number style="width: 100%" placeholder="请输入预警上限" v-decorator="['upperLimit']" :precision="2" :min="0" />
        </a-form-item>

        <a-form-item label="预警下限" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-input-number style="width: 100%" placeholder="请输入预警下限" v-decorator="['lowerLimit']" :precision="2" :min="0" />
        </a-form-item>

        <!-- 型材特有字段 -->
        <template v-if="isProfileType">
          <a-divider orientation="left">型材规格信息</a-divider>
          <a-row :gutter="16">
            <a-col :span="12">
              <a-form-item label="颜色" :labelCol="{ span: 8 }" :wrapperCol="{ span: 16 }">
                <a-input placeholder="请输入颜色" v-decorator="['color']" />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="长度(mm)" :labelCol="{ span: 8 }" :wrapperCol="{ span: 16 }">
                <a-input-number style="width: 100%" placeholder="请输入长度" v-decorator="['length']" :precision="2" />
              </a-form-item>
            </a-col>
          </a-row>
          <a-row :gutter="16">
            <a-col :span="12">
              <a-form-item label="宽度(mm)" :labelCol="{ span: 8 }" :wrapperCol="{ span: 16 }">
                <a-input-number style="width: 100%" placeholder="请输入宽度" v-decorator="['width']" :precision="2" />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="高度(mm)" :labelCol="{ span: 8 }" :wrapperCol="{ span: 16 }">
                <a-input-number style="width: 100%" placeholder="请输入高度" v-decorator="['height']" :precision="2" />
              </a-form-item>
            </a-col>
          </a-row>
          <a-row :gutter="16">
            <a-col :span="12">
              <a-form-item label="重量" :labelCol="{ span: 8 }" :wrapperCol="{ span: 16 }">
                <a-input-number style="width: 100%" placeholder="请输入重量" v-decorator="['weight']" :precision="2" />
              </a-form-item>
            </a-col>
          </a-row>

          <a-divider orientation="left">余料管理</a-divider>
          <a-row :gutter="16">
            <a-col :span="12">
              <a-form-item label="余料上限" :labelCol="{ span: 8 }" :wrapperCol="{ span: 16 }">
                <a-input-number style="width: 100%" placeholder="请输入余料上限" v-decorator="['remnantUpper']" :precision="2" :min="0" />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="余料下限" :labelCol="{ span: 8 }" :wrapperCol="{ span: 16 }">
                <a-input-number style="width: 100%" placeholder="请输入余料下限" v-decorator="['remnantLower']" :precision="2" :min="0" />
              </a-form-item>
            </a-col>
          </a-row>
        </template>

        <!-- 配件和辅件特有字段 -->
        <template v-if="isFittingOrAuxiliaryType">
          <a-form-item label="品牌" :labelCol="labelCol" :wrapperCol="wrapperCol">
            <a-input placeholder="请输入品牌" v-decorator="['brand']" />
          </a-form-item>
          <a-form-item label="颜色" :labelCol="labelCol" :wrapperCol="wrapperCol">
            <a-input placeholder="请输入颜色" v-decorator="['color']" />
          </a-form-item>
        </template>

        <!-- 通用字段 -->
        <a-form-item label="备注" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-textarea placeholder="请输入备注" v-decorator="['remark']" :rows="4" />
        </a-form-item>
        <a-form-item label="状态" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <j-dict-select-tag type="radio" v-decorator="['status', {initialValue: '0'}]" :triggerChange="true" dictCode="wms_material_status" />
        </a-form-item>
      </a-form>
    </a-spin>
  </j-modal>
</template>

<script>
  import { materialAdd, materialEdit } from '@/api/wms'
  import JDictSelectTag from '@/components/dict/JDictSelectTag.vue'
  import JModal from '@/components/jeecg/JModal/JModal'
  import JImageUpload from '@/components/jeecg/JImageUpload'
  import pick from 'lodash.pick'

  export default {
    name: 'MaterialModal',
    components: {
      JDictSelectTag,
      JModal,
      JImageUpload
    },
    data() {
      return {
        form: this.$form.createForm(this),
        title: '操作',
        width: 800,
        visible: false,
        model: {},
        labelCol: {
          xs: { span: 24 },
          sm: { span: 6 }
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 }
        },
        confirmLoading: false,
        validatorRules: {
          materialType: { rules: [{ required: true, message: '请选择物料类型!' }] },
          materialCode: { rules: [{ required: true, message: '请输入物料编号!' }] },
          materialName: { rules: [{ required: true, message: '请输入物料名称!' }] },
          unit: { rules: [{ required: true, message: '请输入单位!' }] }
        },
        disableEdit: false,
        url: {
          add: '/wms/material/add',
          edit: '/wms/material/edit'
        },
        // 物料类型定义
        materialTypes: {
          '1': { name: '型材', code: '型材编号', label: '型材名称' },
          '2': { name: '配件', code: '配件编号', label: '配件名称' },
          '3': { name: '辅件', code: '辅件编号', label: '辅件名称' },
          '4': { name: '成品', code: '成品编号', label: '成品名称' },
          '5': { name: '余料', code: '余料编号', label: '余料名称' },
          '6': { name: '半料', code: '半料编号', label: '半料名称' }
        }
      }
    },
    computed: {
      // 当前物料类型
      currentMaterialType() {
        return this.model.materialType || '1'
      },
      // 是否为型材类型
      isProfileType() {
        return this.currentMaterialType === '1'
      },
      // 是否为配件或辅件类型
      isFittingOrAuxiliaryType() {
        return this.currentMaterialType === '2' || this.currentMaterialType === '3'
      }
    },
    methods: {
      add(materialType = '1') {
        this.edit({
          materialType: materialType, // 默认型材类型
          status: '0' // 默认启用状态
        })
      },
      edit(record) {
        this.form.resetFields()
        this.model = Object.assign({}, record)
        this.visible = true
        this.disableEdit = !!this.model.id

        this.$nextTick(() => {
          // 设置表单值
          this.form.setFieldsValue(pick(
            this.model,
            'materialCode',
            'materialName',
            'materialType',
            'specification',
            'unit',
            'brand',
            'color',
            'length',
            'width',
            'height',
            'weight',
            'materialImage',
            'unitCost',
            'upperLimit',
            'lowerLimit',
            'remark',
            'status'
          ))
        })
      },
      close() {
        this.$emit('close')
        this.visible = false
      },
      handleOk() {
        const that = this
        // 触发表单验证
        this.form.validateFields((err, values) => {
          if (!err) {
            that.confirmLoading = true

            // 处理图片路径
            if (values.materialImage && values.materialCode) {
              // 确保materialImage是字符串
              if (typeof values.materialImage !== 'string') {
                console.warn('物料图片不是字符串类型:', values.materialImage)
                if (values.materialImage && typeof values.materialImage === 'object') {
                  if (values.materialImage.response && values.materialImage.response.message) {
                    values.materialImage = values.materialImage.response.message
                  } else {
                    values.materialImage = JSON.stringify(values.materialImage)
                  }
                } else {
                  values.materialImage = ''
                }
              }

              // 重命名图片，格式：租户ID_物料编码
              const tenantId = this.$store.getters.userInfo.tenantId || ''
              const bizPath = this.getBizPathByType(values.materialType)
              values.materialImage = values.materialImage.replace(new RegExp(`/material/${bizPath}/`), `/material/${bizPath}/${tenantId}_${values.materialCode}_`)
            }

            let formData = Object.assign(this.model, values)

            let obj = {
              ...formData
            }

            if (!this.model.id) {
              // 新增
              materialAdd(obj).then((res) => {
                if (res.success) {
                  that.$message.success(res.message)
                  that.$emit('ok')
                } else {
                  that.$message.warning(res.message)
                }
              }).finally(() => {
                that.confirmLoading = false
                that.close()
              })
            } else {
              // 编辑
              materialEdit(obj).then((res) => {
                if (res.success) {
                  that.$message.success(res.message)
                  that.$emit('ok')
                } else {
                  that.$message.warning(res.message)
                }
              }).finally(() => {
                that.confirmLoading = false
                that.close()
              })
            }
          }
        })
      },
      handleCancel() {
        this.close()
      },
      handleImageChange(value) {
        console.log('物料图片变更:', value)

        // 处理不同类型的输入
        let imagePath = ''

        if (typeof value === 'string') {
          // 如果是字符串，直接使用
          imagePath = value
        } else if (value && typeof value === 'object') {
          // 如果是对象，尝试提取路径
          if (value.response && value.response.message) {
            imagePath = value.response.message
          } else if (Array.isArray(value)) {
            // 如果是数组，提取每个元素的路径并拼接
            imagePath = value.map(item => {
              if (typeof item === 'string') return item
              if (item && item.response && item.response.message) return item.response.message
              return ''
            }).filter(Boolean).join(',')
          } else {
            console.warn('物料图片格式不正确:', JSON.stringify(value))
          }
        }

        console.log('处理后的物料图片路径:', imagePath)

        // 设置表单值
        this.form.setFieldsValue({
          materialImage: imagePath
        })
      },
      // 处理物料类型变更
      handleMaterialTypeChange(value) {
        this.model.materialType = value
        // 更新表单验证规则中的提示信息
        this.updateValidatorRules()
      },
      // 更新表单验证规则
      updateValidatorRules() {
        const typeName = this.getMaterialTypeName()

        this.validatorRules = {
          ...this.validatorRules,
          materialCode: { rules: [{ required: true, message: `请输入${typeName}编号!` }] },
          materialName: { rules: [{ required: true, message: `请输入${typeName}名称!` }] }
        }
      },
      // 获取物料类型名称
      getMaterialTypeName() {
        return (this.materialTypes[this.currentMaterialType] || {}).name || '物料'
      },
      // 获取物料标签
      getMaterialLabel(type) {
        const materialType = this.currentMaterialType
        if (type === 'code') {
          return (this.materialTypes[materialType] || {}).code || '物料编号'
        } else if (type === 'name') {
          return (this.materialTypes[materialType] || {}).label || '物料名称'
        }
        return '物料'
      },
      // 获取业务路径
      getBizPath() {
        return this.getBizPathByType(this.currentMaterialType)
      },
      // 根据类型获取业务路径
      getBizPathByType(type) {
        switch (type) {
          case '1': return 'profile'
          case '2': return 'fitting'
          case '3': return 'auxiliary'
          case '4': return 'product'
          case '5': return 'surplus'
          case '6': return 'semi'
          default: return 'material'
        }
      },
      // 判断是否显示特定字段
      showField(field) {
        const type = this.currentMaterialType

        // 规格字段：配件和辅件显示
        if (field === 'specification') {
          return type === '2' || type === '3'
        }

        return true
      },
      // 处理图片加载错误
      handleImageError(e) {
        console.error('图片加载失败:', e)
        e.target.style.display = 'none'
        const container = e.target.parentNode
        if (container) {
          const icon = document.createElement('i')
          icon.className = 'anticon anticon-picture'
          icon.style.fontSize = '24px'
          icon.style.color = '#d9d9d9'
          container.insertBefore(icon, e.target)

          const errorText = document.createElement('div')
          errorText.innerText = '图片不存在'
          errorText.style.color = '#ff4d4f'
          errorText.style.fontSize = '12px'
          errorText.style.marginTop = '4px'
          container.appendChild(errorText)
        }
      }
    }
  }
</script>
